package com.wz.leetcode.linkedlist;

import com.wz.leetcode.linkedlist.ListNode;

public class AddTowNums_2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode p = l1;
        ListNode q = l2;
        int carry = 0;
        ListNode dummy = new ListNode(-1);
        ListNode result = dummy;
        while (p != null || q != null) {
            int pv = p != null ? p.val : 0;
            int qv = q != null ? q.val : 0;
            int sum = qv + pv + carry;
            int val = sum % 10;
            carry = sum / 10;
            result.next = new ListNode(val);
            result = result.next;
            p = p != null ? p.next : null;
            q = q != null ? q.next : null;
        }
        if (carry != 0) {
            result.next = new ListNode(carry);
        }
        return dummy.next;
    }
}
